<template>
  <view
    class="wrapper"
    :style="specialStyle"
    @touchstart="$emit('closeBubble')"
  >
    <view class="majorFilterContainer">
      <view class="firstListContainer">
        <u-tabs
          :list="majorFirstList"
          bg-color="transparent"
          :height="100"
          inactive-color="#222"
          active-color="#222"
          :bar-style="{ display: 'none' }"
          name="navName"
          is-scroll="true"
          :current="selectedFirstIndex"
          @change="handleFirstItemClick"
          :gutter="28"
          :active-item-style="tabActiveStyle"
        >
        </u-tabs>
      </view>

      <scroll-view
        scroll-y
        scroll-with-animation
        class="recommendArea"
        v-if="selectedFirstIndex == 0"
      >
        <template v-if="from != 'zhadui'">
          <view
            class="recommendItem"
            v-for="(item, index) in recommendData"
            :key="index"
            @click="handleThirdItemClick(item)"
          >
            <view class="recommendImgArea">
              <img class="recommendImg" :src="item.pic" alt="" />
            </view>
            <view class="recommendText">{{ item.positionName }}</view>
          </view>
        </template>
        <template v-if="from == 'zhadui'">
          <view
            class="recommendItem"
            v-for="(item, index) in recommend"
            :key="index"
            @click="handleThirdItemClick(item)"
          >
            <view class="recommendImgArea">
              <img class="recommendImg" :src="item.pic" alt="" />
            </view>
            <view class="recommendText">{{ item.positionName }}</view>
          </view>
        </template>
      </scroll-view>

      <view v-else class="mainListContainer">
        <scroll-view
          scroll-y
          :scroll-top="scrollSecondTop"
          scroll-with-animation
          class="secondPositionList"
          :style="{ height: scrollViewHeight + 'px' }"
        >
          <view
            :class="{
              SecondPositionItem: true,
              'u-line-2': true,
              selectedSecond: item.navId == selectedSecondId,
            }"
            v-for="(item, index) in secondPositionList"
            :key="index"
            :id="`third-${index}`"
            @click="handleSecondItemClick(item, index)"
          >
            <span v-if="item.navName == '热门'" class="hotSecondPosition">
              <img
                src="https://img3.job1001.com/ypMp/elan/images/career/hotSecondPosition.png"
              />
              {{ item.tagName }}</span
            >
            <span v-else>{{ item.navName }}</span>
          </view>
        </scroll-view>
        <scroll-view
          :scroll-y="true"
          scroll-with-animation
          class="thirdPositionList"
          :scroll-into-view="scollThirdToView"
          @scroll.native="handleScroll"
          ref="scollView"
        >
          <view
            class="ThirdPositionItem"
            v-for="(item, index) in secondPositionList"
            :key="index"
            :id="`third-${index}`"
          >
            <view :class="{ thirdTitle: true, fixedTitle: item.isFixTitle }">
              <template v-if="item.navName == '热门'">
                {{ item.navName }}
                <text class="titleTip"
                  >大家都在搜的{{ selectedFirstName }}专业</text
                ></template
              >
              <template v-else>
                {{ item.navName }}
                <text class="titleTip"
                  >({{ item.children.length || "0" }}个)</text
                ></template
              >
            </view>
            <view class="thirdChildrenList">
              <view
                class="thirdChildrenItem"
                v-for="(_item, _index) in item.children"
                :key="_index"
                @click="handleThirdItemClick(_item)"
              >
                <view class="thirdChildrenItemTitle"> {{ _item.navName }}</view>
                <view class="thirdChildrenItemTags">
                  <view class="tagItem" v-if="_item.tagTimeDesc">{{
                    _item.tagTimeDesc
                  }}</view>
                  <view class="tagItem" v-if="_item.tagDesc">{{
                    _item.tagDesc
                  }}</view>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import {
  reqZhituGetCareer,
  reqZhaduiGetCareer,
  reqZhituHasFinished,
  refAddPoint,
} from "@/api/modules/company.js";
import { getNavigationTree, getSonNavigationTree } from "@/api/modules/career";
export default {
  name: "MajorFilterAI",
  props: {
    productSign: {
      type: String,
      default: "",
    },
    rightNumData: {
      type: Object,
      default: () => {},
    },
    from: {
      type: String,
      default: "",
    },
    channel: {
      type: String,
      default: "",
    },
    showHome: {
      type: Boolean,
      default: false,
    },
    cateType: {
      type: String,
      default: "30",
    },
    specialStyle: {
      type: Object,
      default: () => {},
    },
    relevanceCareerId: {
      type: String,
      default: "1",
    },
    rectTop: {
      type: String,
      default: "0",
    },
    pointHome: {
      type: Boolean,
      default: false,
    },
    personId: {
      type: String,
      default: uni.getStorageSync("person-id").slice(2) || undefined,
    },
  },
  data() {
    return {
      // personId: uni.getStorageSync("person-id").slice(2) || undefined,
      positionTree: [], // 职业树
      recommendData: [], // 推荐职业
      recommend: [],
      showRecommend: false,

      majorFirstList: [],
      secondPositionList: [],
      ThirdPositionList: [],
      selectedFirstId: "", //第一层选中的id
      selectedFirstName: "", //第一层选中的名字
      selectedFirstIndex: "", //第一层选中的下标
      scollFirstToView: "", //控制第一层筛选容器滚动的变量
      selectedSecondId: "", //第二层选中的id
      selectedSecondIndex: 0, //第二层选中的下标
      scrollSecondTop: 0, //第二层的滚动高度
      scollThirdToView: "", //控制第三层筛选容器滚动的变量
      distance: 0,
      isClickTab: false, //是否是点击滚动
      secondHeightArr: [], //第二层每一个专业的高度
      heightArr: [], //第三层每一个二级专业的高度
      tabActiveStyle: {
        "justify-content": "center",
        "align-items": "center",
        border: "4rpx solid #f75a3e",
        background: "linear-gradient(180deg, #ffece9 0%, #ffffff 100%)",
        "border-radius": "12rpx",
        "line-height": "98rpx",
      },
      scrollViewHeight: 600,
      infoId: "",
    };
  },
  methods: {
    goBackHome() {
      uni.setStorageSync("person-id", "");
      uni.navigateBack();
      // console.log("MajorFilterAI 返回首页");
    },
    commitBuringPoint() {
      var modelType = "";
      if (this.from == "zhadui") {
        modelType = "demonstrate";
      }
      const params = {
        optCode: "enterMajorFilterAI",
        platform: "1",
        personId: this.personId,
        moduleType: modelType,
      };

      refAddPoint(params).then((res) => {
        if (res.code == 200) {
          // console.log("commitBuringPoint", res);
        }
      });
    },

    // home埋点数据统计
    pointCount(step) {
      if (this.pointHome) {
        const params = {
          personId: this.personId,
          platform: "1",
          optCode: "aiPromotion",
          subOptCode: step == 4 ? "点击了职业" : "进入面评",
          optIndex: step,
          description: "首页AI面评推广",
          moduleType: "demonstrate", // 模块类型(zt:职途，zph：招聘会活动-百职万岗，demonstrate：演示-扎堆)
        };
        refAddPoint(params).then((res) => {
          if (step == 4) {
            // console.log("🚀 ~ refAddPoint ~4~ res:", res);
          } else {
            // console.log("🚀 ~ refAddPoint ~5~ res:", res);
          }
        });
      }
    },

    //专科本科改变将index设为0
    currentIndexZero() {
      this.selectedFirstIndex = 0;
    },
    handleFirstItemClick(index) {
      // console.log("handleFirstItemClick:" + index);
      this.selectedFirstIndex = index;
      if (index == 0) {
        this.showRecommend = true;
        return;
      }
      this.selectedFirstId = "";
      const item = this.majorFirstList[index];
      this.selectedFirstId = item.navId;
      this.selectedFirstName = item.navName;
      this.scollFirstToView = "first-" + index;
      this.reqgetSonNavigationTree(item.navId);
    },
    handleSecondItemClick(item, index) {
      console.log("handleSecondItemClick", item, index);
      if (this.isClickTab) return;
      this.isClickTab = true;
      setTimeout(() => {
        this.isClickTab = false;
      }, 500);
      this.selectedSecondId = item.navId;
      this.selectedSecondIndex = index;
      this.scollThirdToView = null;
      this.$nextTick(() => {
        this.scollThirdToView = "third-" + index;
      });
    },
    handleThirdItemClick(_item) {
      // console.log("handleThirdItemClick", _item);
      // this.personId = uni.getStorageSync("person-id").slice(2) || undefined;
      this.pointCount(4);
      if (!this.personId) {
        this.$emit("needlogin");
        return;
      }

      this.pointCount(5);
      if (_item.positionId) {
        // console.log("checkStartOnAIInterView positionId");
        this.positionId = _item.positionId;
        this.checkStartOnAIInterView(_item.positionId);
      } else {
        // console.log("checkStartOnAIInterView valueId");
        this.positionId = _item.valueId;
        this.checkStartOnAIInterView(_item.valueId);
      }
    },

    checkStartOnAIInterView(positionId) {
      console.log("checkStartOnAIInterView");
      this.isLoading = true;
      let modelType = "";
      if (this.from == "zhadui") {
        modelType = "demonstrate";
      }
      let params = {
        personId: this.personId,
        positionId: positionId,
        modelType: modelType,
      };
      reqZhituHasFinished(params)
        .then((res) => {
          this.isLoading = false;
          if (res.code == 200) {
            let type = this.from == "zhadui" ? "zhadui" : "zhitu";
            if (res.data.status == "not_finished") {
              let record = res.data.id;
              this.record = record;
              let infoId = +res.data.infoId;
              this.infoId = infoId;
              this.$emit(
                "onGoToInterview",
                type,
                positionId,
                this.record,
                this.channel,
                this.infoId
              );
            } else {
              // if (this.productSign == "ZHITU_TOC_SERVICE") {
              // if (this.rightNumData.useNum < this.rightNumData.ownNum) {
              uni.navigateTo({
                url:
                  "/pagesSub/companyCenter/interviewAI/room/interviewReady?from=" +
                  type +
                  "&careerId=" +
                  positionId +
                  "&channel=" +
                  this.channel +
                  "&personId=" +
                  this.personId,
              });
              // } else {
              //   console.log('进入到marjoFilter权益不足');
              //   uni.showToast({
              //     icon: "none",
              //     title: "权益次数不足~",
              //   });
              // }
              // } else {
              //   uni.navigateTo({
              //     url:
              //       "/pagesSub/companyCenter/interviewAI/room/interviewReady?from=" +
              //       type +
              //       "&careerId=" +
              //       positionId +
              //       "&channel=" +
              //       this.channel,
              //   });
              // }
            }
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "none",
            });
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },
    handleScroll(e) {
      if (this.isClickTab) return;
      this.$emit("closeBubble");
      let scrollTop = e.detail.scrollTop; //获取距离顶部的距离;
      //现在的item的高度
      const nowHeight = this.heightArr[this.selectedSecondIndex];
      //上一个的高度
      const preHiehgt = this.heightArr[this.selectedSecondIndex - 1];
      //处理第三层的滚动
      if (scrollTop > nowHeight) {
        if (this.secondPositionList.length > this.selectedSecondIndex + 1) {
          this.selectedSecondId =
            this.secondPositionList[this.selectedSecondIndex + 1].positionId;
          this.selectedSecondIndex += 1;
          //如果滚动到顶部以后了，那就得固定一下title
          this.$set(
            this.secondPositionList[this.selectedSecondIndex],
            "isFixTitle",
            true
          );
        }
      } else if (scrollTop < preHiehgt) {
        if (this.secondPositionList[this.selectedSecondIndex - 1]) {
          this.selectedSecondId =
            this.secondPositionList[this.selectedSecondIndex - 1].positionId;
          this.selectedSecondIndex -= 1;
          this.$set(
            this.secondPositionList[this.selectedSecondIndex],
            "isFixTitle",
            true
          );
        }
      }
      //处理二级跟随滚动
      this.scrollSecondTop =
        this.secondHeightArr[this.selectedSecondIndex] -
        parseInt(this.specialStyle.height.slice(0, -2) / 2);
    },
    cacHeight() {
      this.$nextTick(() => {
        let list = [];
        let height = 0;
        const query = uni.createSelectorQuery().in(this);
        query.selectAll(".ThirdPositionItem").boundingClientRect();
        query.exec((res) => {
          res[0].forEach((item) => {
            // height += parseInt(item.height);
            // list.push(height);
            height += parseInt(100);
            list.push(height);
          });
          this.heightArr = list;
        });
      });
    },
    //计算二级的每个高度
    cacSecondHeight() {
      this.$nextTick(() => {
        let list = [];
        let height = 0;
        const query = uni.createSelectorQuery().in(this);
        query.selectAll(".SecondPositionItem").boundingClientRect();
        query.exec((res) => {
          res[0].forEach((item) => {
            height += parseInt(item.height);
            list.push(height);
          });
          this.secondHeightArr = list;
        });
      });
    },

    // 获取职业列表(数据写死固定的)
    zhituGetStartInfo() {
      // console.log(
      //   "MajorFilterAI 职途选择职业面评" +
      //     this.relevanceCareerId +
      //     " personId:" +
      //     this.personId
      // );
      this.isLoading = true;
      let params = {
        personId: this.relevanceCareerId,
      };
      reqZhituGetCareer(params)
        .then((res) => {
          this.isLoading = false;
          if (res.code == 200) {
            this.recommendData = res.data.recommend;
          } else {
            uni.showToast({
              title: res.status_desc,
              icon: "error",
            });
          }
        })
        .catch((err) => {
          this.isLoading = false;
        });
    },

    zhaduiGetStartInfo() {
      this.isLoading = true;
      // console.log(
      //   "MajorFilterAI 扎堆选择职业面评 relevanceCareerId:" +
      //     this.relevanceCareerId +
      //     " personId:" +
      //     this.personId
      // );
      let id = "";
      if (this.personId) {
        id = this.personId;
      } else {
        id = this.relevanceCareerId;
      }
      let params = {
        personId: id,
      };
      setTimeout(() => {
        reqZhaduiGetCareer(params)
          .then((res) => {
            this.isLoading = false;
            if (res.code == 200) {
              // console.log("扎堆推荐", res);
              this.recommend = res.data;
            } else {
              uni.showToast({
                title: res.status_desc,
                icon: "error",
              });
            }
          })
          .catch((err) => {
            this.isLoading = false;
          });
      }, 500);
    },

    firstLevel(data) {
      // console.log("firstLevel data", data);
      this.majorFirstList = data || [];
      this.majorFirstList.unshift({
        positionId: "-1",
        positionName: "推荐",
      });
      // console.log("firstLevel majorFirstList", this.majorFirstList);
      if (data.length > 0) {
        let obj = data[0];
        this.selectedFirstId = obj.positionId;
        this.selectedFirstName = obj.positionName;
        this.secondLevel(obj.children);
        this.scollFirstToView = ""; //需要先重置一下
        setTimeout(() => {
          this.scollFirstToView = "first-0"; //重置一下第三层滚动
        });
      }
    },
    secondLevel(data) {
      if (!data || data.length == 0) {
        return;
      }
      this.secondPositionList = data || [];
      let secondObj = data[0];
      this.selectedSecondId = secondObj.positionId;

      this.cacSecondHeight();
      this.cacHeight();
      this.selectedSecondIndex = 0;
      this.isClickTab = true;
      setTimeout(() => {
        this.isClickTab = false;
      }, 300);
      this.scollThirdToView = ""; //需要先重置一下
      setTimeout(() => {
        this.scollThirdToView = "third-0"; //重置一下第三层滚动
        this.$set(
          this.secondPositionList[this.selectedSecondIndex],
          "isFixTitle",
          true
        );
      });
    },
    // 获取第一层
    reqgetNavigationTree() {
      getNavigationTree({})
        .then((res) => {
          if (res.code == 200) {
            this.majorFirstList = res.data || [];
            this.majorFirstList.unshift({
              navId: "-1",
              navName: "推荐",
            });
            // console.log(
            //   "reqgetNavigationTree:",
            //   this.majorFirstList,
            //   res.data.length
            // );
            if (res.data.length) {
              this.selectedFirstId = res.data[0].navId;
              this.selectedFirstName = res.data[0].navName;
              // console.log(
              //   res.data[0] +
              //     " " +
              //     this.selectedFirstId +
              //     " " +
              //     this.selectedFirstName
              // );
              this.reqgetSonNavigationTree(res.data[0].navId);
              this.scollFirstToView = ""; //需要先重置一下
              setTimeout(() => {
                this.scollFirstToView = "first-0"; //重置一下第三层滚动
              });
            }
          }
        })
        .catch((err) => {});
    },

    // 获取第二层
    reqgetSonNavigationTree(navId) {
      // console.log("reqgetSonNavigationTree navId:", navId);

      //如果是推荐就不请求
      if (navId == -1) return;
      //根据一级专业Id获取二级和三级列表，每次tab点击都会调用
      getSonNavigationTree({
        navId: navId,
        levelNum: 1,
      })
        .then((res) => {
          // console.log("reqgetSonNavigationTree res:", res);
          if (res.code == 200) {
            this.secondPositionList = res.data[0].children || [];
            this.selectedSecondId = res.data[0].children[0].navId;
            this.cacSecondHeight();
            this.cacHeight();
            this.selectedSecondIndex = 0;
            this.isClickTab = true;
            setTimeout(() => {
              this.isClickTab = false;
            }, 300);
            this.scollThirdToView = ""; //需要先重置一下
            setTimeout(() => {
              this.scollThirdToView = "third-0"; //重置一下第三层滚动
              this.$set(
                this.secondPositionList[this.selectedSecondIndex],
                "isFixTitle",
                true
              );
            });
          }
        })
        .catch((err) => {});
    },
  },
  created() {
    // console.log("MajorFilterAI created from:" + this.from);
  },
  mounted() {
    // console.log("MajorFilterAI mounted from:" + this.from);
    if (this.from == "zhadui") {
      this.zhaduiGetStartInfo();
      this.zhituGetStartInfo();
    } else {
      this.zhituGetStartInfo();
    }

    this.reqgetNavigationTree();

    this.commitBuringPoint();
  },
  destroyed() {
    // console.log("MajorFilterAI destroyed");
  },
  watch: {
    from(newValue, oldValue) {
      // console.log("MajorFilterAI from值改变:" + newValue);
      if (newValue) {
        if (this.from == "zhadui") {
          this.zhaduiGetStartInfo();
        }
      }
    },
    cateType(newValue, oldValue) {
      // console.log("MajorFilterAI cateType值改变:" + newValue);
      if (newValue) {
        if (this.from == "zhadui") {
          this.zhaduiGetStartInfo();
        } else {
          this.zhituGetStartInfo();
        }
      }
    },
    rectTop(newValue, oldValue) {
      // console.log(
      //   "MajorFilterAI rectTop值改变:" + newValue + " this.from:" + this.from
      // );
      if (newValue) {
        let searchBottom = newValue;

        const { screenHeight } = uni.getSystemInfoSync();
        // console.log(
        //   "screenHeight:" + screenHeight + " searchBottom:" + searchBottom
        // );
        this.scrollViewHeight = screenHeight;
        // console.log("MajorFilterAI scrollViewHeight:" + this.scrollViewHeight);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  margin-top: 26rpx;
  width: 100vw;
  min-height: 400rpx;
  .majorFilterContainer {
    .firstListContainer {
      height: 100rpx;
      width: 100vw;
      margin-bottom: 38rpx;
      .firstListItem {
        display: inline-flex;
        justify-content: center;
        align-items: center;
        scroll-snap-align: center; /* 设置吸附位置 */
        height: 100rpx;
        padding: 0 28rpx;
        margin-right: 16rpx;
        border-radius: 12rpx;
        border: 2rpx solid #e4e5f5;
        background: linear-gradient(180deg, #ebf5fe 0%, #ffffff 100%);
        &.selectedFirst {
          border: 4rpx solid #f75a3e;
          background: linear-gradient(180deg, #ffece9 0%, #ffffff 100%);
        }
        &:last-of-type {
          margin-right: 0rpx;
        }
      }
    }
  }

  .recommendArea {
    display: flex;
    flex-wrap: wrap;
    height: calc(100vh - 582rpx);
    .recommendItem {
      width: 30%;
      height: 200rpx;
      display: inline-flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin: 10rpx;
    }
    .recommendImgArea {
      width: 124rpx;
      height: 124rpx;
      border-radius: 70rpx;
      background-color: #ebebeb;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      padding-top: 12rpx;
    }
    .recommendImg {
      width: 100%;
      height: 100%;
    }
    .recommendText {
      align-items: center;
      color: #222222;
      margin-top: 14rpx;
    }
  }
  .mainListContainer {
    display: flex;
    .secondPositionList {
      // height: calc(100vh - 328px) !important;
      height: calc(100vh - 700rpx) !important;
      background-color: #f4f6f8;
      .SecondPositionItem {
        display: flex;
        align-items: center;
        padding-left: 32rpx;
        height: 100rpx;
        background: #f4f6f8;
        color: #666666;
        span {
          text-align: left;
          max-width: 160rpx;
          font-size: 28rpx;
        }
        .hotSecondPosition {
          display: inline-flex;
          justify-content: flex-start;
          align-items: center;
          img {
            width: 28rpx;
            height: 36rpx;
            margin-right: 14rpx;
          }
        }
      }
      .selectedSecond {
        position: relative;
        background: #ffffff;
        font-weight: bold;
        color: #222222;
        &::after {
          content: "";
          position: absolute;
          bottom: -30rpx;
          right: 0rpx;
          height: 30rpx;
          width: 30rpx;
          background-image: url($img-base + "career/positionDictionary/radiuBorder.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
        &::before {
          content: "";
          position: absolute;
          top: -30rpx;
          right: 0rpx;
          height: 30rpx;
          width: 30rpx;
          background-image: url($img-base + "career/positionDictionary/topRadiuBorder.png");
          background-repeat: no-repeat;
          background-size: 100% 100%;
        }
      }
    }
    .thirdPositionList {
      position: relative;
      // height: calc(100vh - 285px);
      height: calc(100vh - 690rpx) !important;

      background-color: white;
      margin-left: -2rpx;
      .ThirdPositionItem {
        display: flex;
        flex-direction: column;
        border-bottom: 10rpx solid #f4f6f7;
        &:last-of-type {
          overflow: hidden;
          border-bottom: none;
          padding-bottom: 100rpx;
        }
        .thirdTitle {
          display: flex;
          align-items: center;
          width: 538rpx;
          height: 100rpx;
          padding: 0rpx 32rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          .titleTip {
            font-size: 26rpx;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #888888;
            line-height: 30rpx;
            padding-left: 16rpx;
          }
        }
        .fixedTitle {
          position: sticky;
          top: 0;
          z-index: 2;
          background-color: white;
        }
        .thirdChildrenList {
          display: flex;
          flex-direction: column;
          .thirdChildrenItem {
            display: flex;
            flex-direction: column;

            padding: 24rpx 0;
            margin: 0 32rpx;
            border-bottom: 1.2rpx solid #f5f5f5;
            .thirdChildrenItemTitle {
              font-size: 28rpx;
              font-family: PingFangSC;
              font-weight: bold;
              color: #222222;
              line-height: 30rpx;
            }
            .thirdChildrenItemTags {
              display: flex;
              .tagItem {
                display: flex;
                align-items: center;
                height: 30rpx;
                font-size: 20rpx;
                padding: 0 6rpx;
                background: rgba(255, 119, 49, 0.05);
                border-radius: 6rpx;
                border: 1rpx solid #ff836c;
                color: #fa7259;
                margin-right: 16rpx;
              }
            }
          }
        }
      }
    }
  }
}
.u-tab-item {
  border: none;
  background: #f5f5f5;
}
</style>
